package com.bosssoft.boss_exam_web.Controller;

import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.enums.business.ApplicantEnum;
import com.bosssoft.boss_exam_core.enums.business.ResumeEnum;
import com.bosssoft.boss_exam_core.exception.DeleteEntityException;
import com.bosssoft.boss_exam_core.exception.QueryDataException;
import com.bosssoft.boss_exam_core.exception.ReflectionException;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.*;
import com.bosssoft.boss_exam_db.service.busines.ApplicantService;
import com.bosssoft.boss_exam_db.service.busines.JobService;
import com.bosssoft.boss_exam_db.service.busines.ResumeKeyService;
import com.bosssoft.boss_exam_db.service.busines.ResumeParameterService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.bosssoft.boss_exam_web.common.annotation.LoginApplicant;
import com.bosssoft.boss_exam_web.model.dto.ApplicantResumeDTO;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @Author lys(cherish)
 * @Phone 17720799636
 * @Date  2019/3/14
 * @Description 应聘人服务
 * @since JDK 1.8
 **/
@RestController
@Validated
@Slf4j
@Api(value="应聘人控制器")
public class ApplicantController {

    //注入application服务
    @Autowired
    private ApplicantService applicantService;

    //注入简历项服务
    @Autowired
    private ResumeParameterService resumeParameterService;

    //注入简历键服务
    @Autowired
    private ResumeKeyService resumeKeyService;

    //注入岗位服务
    @Autowired
    private JobService jobService;



    @ApiOperation(value="应聘人添加", notes="添加应聘人，只包含基本信息" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="applicant", value="应聘人对象json", dataType = "Applicant", required=true, dataTypeClass=Applicant.class),
    })
    @PostMapping("/pc/applicant/create")
    public Object create( @Valid @RequestBody Applicant applicant) {

        int recordNum = applicantService.saveNotNull(applicant);
        if (recordNum==1){
            return ResponseUtil.ok(applicant);
        }else {
            log.error("【系统错误】 保存失败");
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }

    @ApiOperation(value="应聘人查询", notes="可根据用户名、学历、毕业学校查询用户" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="username", value="应聘人名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="education", value="学历名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="school", value="毕业学校", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })

    @GetMapping("/admin/applicant/list")
    public Object list(@LoginAdmin String  adminId,
                       @RequestParam  String username,
                       @RequestParam String education,
                       @RequestParam String school,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        PageInfo<Applicant> applicantPageInfo = applicantService.queryByCondition(username,education,school,page,limit,sort,order);
        if(applicantPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", applicantPageInfo.getTotal());
            data.put("items", applicantPageInfo.getList());
            return ResponseUtil.ok(data);
        }
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/3/14
     * @Description 将应聘人的基本信息封装好，供简历查询服务
     *
     * @Param [] 无
     * @Return java.util.List<com.bosssoft.boss_exam_web.model.dto.ApplicantResumeDTO>
     * @Exception //TODO
     * @since JDK 1.8
     **/
    public List<ApplicantResumeDTO> makeResumeData(Applicant applicant) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //存放所有简历DTO信息的数据容器
        ArrayList<ApplicantResumeDTO> list = new ArrayList<ApplicantResumeDTO>(10);
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_USERNAME.getKey(), ApplicantEnum.APPLICANT_USERNAME.getDesc(), applicant.getUsername()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_BIRTHDAY.getKey(), ApplicantEnum.APPLICANT_BIRTHDAY.getDesc(), applicant.getBirthday()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_SCHOOL.getKey(), ApplicantEnum.APPLICANT_SCHOOL.getDesc(), applicant.getSchool()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_MAJOR.getKey(), ApplicantEnum.APPLICANT_MAJOR.getDesc(), applicant.getMajor()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_MAIL.getKey(), ApplicantEnum.APPLICANT_MAIL.getDesc(), applicant.getMail()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_PHONE.getKey(), ApplicantEnum.APPLICANT_PHONE.getDesc(), applicant.getPhone()));
        //获取岗位名称
        String jobId = applicant.getJobId();
        Job job = jobService.selectByKey(jobId);
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_APPLICANT_JOB.getKey(), ApplicantEnum.APPLICANT_APPLICANT_JOB.getDesc(),job.getName()));
        list.add(new ApplicantResumeDTO(ResumeEnum.INFOType_BASE.getKey(), ApplicantEnum.APPLICANT_TYPE.getKey(), ApplicantEnum.APPLICANT_AVATAR.getKey(), ApplicantEnum.APPLICANT_AVATAR.getDesc(), applicant.getAvatar()));
        return list;
    }


    @ApiOperation(value="应聘人详细信息查询", notes="可根据应聘人的ID查询详情" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="应聘人ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/admin/applicant/read")
    public Object read(@LoginAdmin String adminId, @NotNull String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        //        查询应聘人基本信息
        //填充信息
        List<ApplicantResumeDTO> applicantResumeDTOS=null;
        Applicant applicant = null;
        try {
            applicant = applicantService.selectByKey(id);
            applicantResumeDTOS = makeResumeData(applicant);
        } catch (NoSuchMethodException |InvocationTargetException|IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException();
        } catch (Exception e) {
            log.error("【系统错误】 读取应聘人异常"+e);
            throw  new QueryDataException();
        }
        //查询应聘人简历
        List<ResumeParameter> resumeParameters =resumeParameterService.queryByApplicantId(id);
        //  填充简历信息
        List<ApplicantResumeDTO> finalApplicantResumeDTOS = applicantResumeDTOS;
        resumeParameters.stream().forEach(r -> {
            ResumeKey resumeKey = null;
            try {
                resumeKey = resumeKeyService.selectByKey(r.getResumeKeyId());
            } catch (NoSuchMethodException |InvocationTargetException|IllegalAccessException e) {
                log.error("【系统错误】 反射操作异常"+e);
                throw  new ReflectionException();
            } catch (Exception e) {
                log.error("【系统错误】 读取应聘人异常"+e);
                throw  new QueryDataException();
            }
            finalApplicantResumeDTOS.add(new ApplicantResumeDTO(ResumeEnum.INFOType_Resume.getKey(), resumeKey.getCategory(), resumeKey.getResumeKey(), resumeKey.getResumeKeyDesc(),r.getValue()));
        });
        return ResponseUtil.ok(applicantResumeDTOS);
    }


    // todo 更新应聘人暂未实现
    @PostMapping("/admin/applicant/update")
    public Object update(@LoginAdmin Integer adminId,@RequestParam String applicantId, @RequestBody  HashMap<String,Object> resumeObj) {
        if (applicantId == null) {
            return ResponseUtil.unlogin();
        }

        //将简历的键值设置到简历表中
//        resumeObj.forEach((key,value)->{
//        });
//        Object error = validate(applicant);
//        if (error != null) {
//            return error;
//        }
//        if (applicantService.updateNotNull(applicant) == 0) {
//            return ResponseUtil.updatedDataFailed();
//        }
//        return ResponseUtil.ok(applicant);
        return null;
    }

    @ApiOperation(value="应聘人删除", notes="可根据应聘人的ID逻辑删除应聘人" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="应聘人ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/admin/applicant/delete")
    public Object delete(@LoginAdmin String adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Applicant applicant = new Applicant();
        applicant.setId(id);
        try {
            Boolean result=applicantService.deleteApplicantAndResume(applicant);
            if(result){
                return ResponseUtil.ok();
            }else {
                log.info("【业务错误】 逻辑删除应聘者异常");
                throw  new DeleteEntityException();
            }
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }

    @ApiOperation(value="查询手机端当前登入的应聘人信息", notes="根据当前登入的应聘人查询应聘人信息" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="applicantId", value="当前登入的应聘人ID", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/phone/applicant/info")
    public Object phoneGetInfo(@LoginApplicant String applicantId){
        Applicant applicant = null;
        try {
            applicant = applicantService.selectByKey(applicantId);
        }catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e) {
            log.info("【业务错误】 获取管理员信息异常"+e);
            throw  new QueryDataException();
        }
        //屏蔽密码
        applicant.setPassword("");
        return  ResponseUtil.ok("当前用户信息",applicant);
    }

    @ApiOperation(value="查询PC端当前登入的应聘人信息", notes="根据当前登入的应聘人查询应聘人信息" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="applicantId", value="当前登入的应聘人ID", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/pc/applicant/info")
    public Object pcGetInfo(@LoginApplicant String applicantId){
        Applicant applicant = null;
        try {
            applicant = applicantService.selectByKey(applicantId);
        }catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e) {
            log.info("【业务错误】 获取管理员信息异常"+e);
            throw  new QueryDataException();
        }
        //屏蔽密码
        applicant.setPassword("");
        return  ResponseUtil.ok("当前用户信息",applicant);
    }
}
